package cn.kgc.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.kgc.springcloud.client.TagClient;
import cn.kgc.springcloud.commons.ResponseResult;
import cn.kgc.springcloud.entity.Clazz;
import cn.kgc.springcloud.entity.Tag;
import cn.kgc.springcloud.mapper.ClazzMapper;
import cn.kgc.springcloud.service.ClazzService;
import cn.kgc.springcloud.vo.ClazzVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author mengshun
* @description 针对表【t_clazz】的数据库操作Service实现
* @createDate 2024-05-08 10:37:41
*/
@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService{

    @Resource
    private TagClient tagClient;

    @Override
    public ResponseResult clazzList() {

        // 查询班级列表
        List<Clazz> clazzes = baseMapper.selectList(null);

        List<ClazzVO> collect = clazzes.stream().map(clazz -> {
            ClazzVO clazzVO = new ClazzVO();
            BeanUtils.copyProperties(clazz,clazzVO);
            // 获取标签id
            Integer tagId = clazz.getTagid();
            Tag tag = tagClient.getOneTag(tagId);
            clazzVO.setTag(tag);

            return clazzVO;
        }).collect(Collectors.toList());


        return ResponseResult.success().data(collect);
    }

    @Override
    public ResponseResult addClazz(MultipartFile file, String name, Integer tagId) {

        // 文件上传   oss  -> url
        if (file.isEmpty()) {
            return  ResponseResult.fail().message("文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);

        String uuid = IdUtil.simpleUUID();
        String lastName = uuid+"."+filenameExtension;

        File file1 = new File("D:/upload/springcloud/");

        if (!file1.exists()) {
            file1.mkdir();
        }

        File file2 = new File(file1, lastName);
        Clazz clazz = new Clazz();
        try {
            file.transferTo(file2);
            clazz.setName(name);
            clazz.setTagid(tagId);
            clazz.setPath(lastName);
            baseMapper.insert(clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.success().message("班级信息添成功").data(clazz);
    }
}




